package com.foruo.sc.log.server.config;

import com.foruo.sc.log.server.rabbit.Receive;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * rabbit配置
 * @author GaoYuan
 * @date 2018/4/9 下午3:55
 */
@Configuration
public class RabbitServerConfig {

    /** 队列名称 */
    public final static String queueName = "sc-log";

    @Bean
    Queue queue() {
        return new Queue(queueName, false);
    }

    /** 指定消息按什么规则，路由到哪个Queue，Message消息先要到达Exchange，在Server中承担着从Produce接收Message的责任 */
    @Bean
    TopicExchange exchange() {
        return new TopicExchange("sc-log-exchange");
    }

    /** 绑定queue与exchange */
    @Bean
    Binding binding(Queue queue, TopicExchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with(queueName);
    }

    @Bean
    SimpleMessageListenerContainer container(ConnectionFactory connectionFactory,
                                             MessageListenerAdapter listenerAdapter) {
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.setQueueNames(queueName);
        container.setMessageListener(listenerAdapter);
        return container;
    }

    @Bean
    MessageListenerAdapter listenerAdapter(Receive receiver) {
        return new MessageListenerAdapter(receiver, "receiveMessage");
    }

}
